package com.woniuxy.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

//基于ini配置文件的自定义域
public class MyRealmDemo extends AuthorizingRealm{
    private final String REALMNAME="MyRealmDemo";
    //授权的，会抛出这个信息交给Shiro底层(SecurityManager)来帮我们控制逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //不建议直接使用魔法值，判断是否是有下列的认证返回的数据传入的
        if (principals.getRealmNames().contains(REALMNAME)) {
            //来自于认证方法return中封装的数据，未来，下面就直接封装TOKEN
            String username = principals.getPrimaryPrincipal()+"";
            //模拟数据库去角色表和权限表中查询数据出来，并封装到AuthorizationInfo里面
            Set<String> roles = new HashSet<>();//封装角色，数据库查出来封装到set就会去重
            roles.add("admin");
            roles.add("manager");
            roles.add("tourist");
            Set<String> perms = new HashSet<>();//封装权限
            perms.add("manager:add");
            perms.add("manager:edit");
            perms.add("manager:del");
            perms.add("manager:find");
            //封装
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setRoles(roles);
            simpleAuthorizationInfo.setStringPermissions(perms);
            return simpleAuthorizationInfo;
        }
        return null;
    }
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof UsernamePasswordToken){
            UsernamePasswordToken usernamePasswordToken =   (UsernamePasswordToken)token;
            String username = usernamePasswordToken.getUsername();
            //通过username去数据库查询数据，这里就模拟数据对象
            String password = "123456";
            //判断登录的密码是否和传入的密码一致。
            if (new String(usernamePasswordToken.getPassword()).equals(password)) {
                System.out.println("登录成功");
                return new SimpleAuthenticationInfo(username,password,REALMNAME);
            }else {
                return null;
            }
        }
        return null;
    }
}
